package com.example.servlet;

import com.example.dao.GuitarDao;
import com.example.dao.PurchaseRecordDao;
import com.example.entity.Customer;
import com.example.entity.Guitar;
import com.example.entity.PurchaseRecord;
import com.google.gson.Gson;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@WebServlet("/cart")
public class CartServlet extends HttpServlet {
    private GuitarDao guitarDao = new GuitarDao();
    private PurchaseRecordDao purchaseRecordDao = new PurchaseRecordDao();
    private Gson gson = new Gson();

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        HttpSession session = request.getSession();
        Map<String, Object> result = new HashMap<>();
        
        if ("add".equals(action)) {
            // 获取当前登录用户
            Customer customer = (Customer) session.getAttribute("customer");
            if (customer == null) {
                result.put("success", false);
                result.put("message", "请先登录");
                sendJsonResponse(response, result);
                return;
            }

            // 获取吉他ID并查询吉他信息
            int guitarId = Integer.parseInt(request.getParameter("guitarId"));
            Guitar guitar = guitarDao.findById(guitarId);
            if (guitar == null) {
                result.put("success", false);
                result.put("message", "吉他不存在");
                sendJsonResponse(response, result);
                return;
            }

            // 创建购买记录
            PurchaseRecord record = new PurchaseRecord();
            record.setCustomerId(customer.getId());
            record.setGuitarId(guitarId);
            record.setPrice(guitar.getPrice());
            record.setPurchaseTime(new Date());

            // 保存购买记录
            purchaseRecordDao.add(record);

            result.put("success", true);
            sendJsonResponse(response, result);
        }
    }

    private void sendJsonResponse(HttpServletResponse response, Map<String, Object> data) 
            throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(gson.toJson(data));
    }
} 